package com.zzx.magic.controller;

import com.alibaba.fastjson.JSON;
import com.zzx.magic.entity.Amount;
import com.zzx.magic.entity.NativePayParams;
import com.zzx.magic.entity.NotifyDto;
import com.zzx.magic.service.NativePayService;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Zhangxx
 * @Date 2024/6/13 11:26
 */
@RestController
@RequestMapping("/native")
@Log4j2
public class WxPayController {

    @RequestMapping("/pay")
    public void pay () {

    }

    private String mchId = "xxx"; //商户号
    //private String appId = "wx6592a2db3f85ed25"; //应用号
    private String appId = "xxx"; //应用号
    private String privateKey = "xx" + "-----END PRIVATE KEY-----\n"; //私钥字符串
    private String mchSerialNo = "xxx"; //商户证书序列号
    private String apiV3Key = "xxx"; //V3密钥
    CloseableHttpClient httpClient;

    public void setup() throws IOException {
        // 加载商户私钥（privateKey：私钥字符串）
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),apiV3Key.getBytes("utf-8"));

        // 初始化httpClient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
    }

    public void after() throws IOException {
        httpClient.close();
    }

    public void testNativePay() throws Exception{
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
        // 请求body参数

        Amount amount = Amount.builder().currency("CNY").total(1).build();

        NativePayParams nativePayParams = NativePayParams.builder().appid(appId)
                .description("百世可乐")
                .mchid(mchId)
                .notify_url("http://localhost:8080")
                .out_trade_no("AEFA234DAF342342FRADFAS1")
                .amount(amount)
                .build();


        String reqdata = JSON.toJSONString(nativePayParams);
        StringEntity entity = new StringEntity(reqdata,"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
            } else if (statusCode == 204) { //处理成功，无返回Body
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }


    }

    @Autowired
    private NativePayService nativePayService;

    @PostMapping("/notify")
    public Map<String,String> nativeNotify(@RequestBody NotifyDto dto){
        System.out.println("--微信回调--");
        Map<String ,String> map = null;
        try {
            nativePayService.notify(dto);
        } catch (Exception e) {
            e.printStackTrace();
            map = new HashMap<>();
            map.put("code","FAIL");
            map.put("message","失败");
        }

        return map;
    }
}